﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.Mvc;
using System.IO;
using Recaptcha;
using System.Threading;

namespace Helpers
{
    /// <summary>
    /// Extension method to HtmlHelper class
    /// </summary>
    public static class ReCaptchaHelper
    {
        private const string MY_PUBLIC_KEY = "6LeQYLwSAAAAAI_ZWTBWwGbrrCKzOv7GPQM0irVk";
        private const string MY_PRIVATE_KEY = "6LeQYLwSAAAAAFHmoHjhZFuDXFJXq26QDw8jUHcN";
        private static List<string> RECAPTCHA_LANGUAGES = new List<string>() { "en", "pt" };
        private const string RECAPTCHA_ID = "recaptcha";
        private const string RECAPTCHA_THEME = "clean";


        /// <summary>
        /// Method used to call the Google's captcha script e push it to the html page
        /// </summary>
        /// <param name="helper">Extension method to HtmlHelper</param>
        /// <returns></returns>
        public static string GenerateCaptcha(this HtmlHelper helper)
        {
            string localizedHtml;
            HtmlTextWriter htmlWriter = new HtmlTextWriter(new StringWriter());;

            using (var captchaControl = new RecaptchaControl
            {
                ID = RECAPTCHA_ID,
                Theme = RECAPTCHA_THEME,
                PublicKey = MY_PUBLIC_KEY,
                PrivateKey = MY_PRIVATE_KEY
            })
            {
                try
                {                  
                    captchaControl.RenderControl(htmlWriter);
                    string html = htmlWriter.InnerWriter.ToString();
                    // Take the html that the ReCaptcha.dll generates and add support for localization.
                    
                    var culture = Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToLower();

                    if (RECAPTCHA_LANGUAGES.Contains(culture))
                    {
                        localizedHtml = html.Replace("RecaptchaOptions = {", "RecaptchaOptions = { lang : '" + culture + "',");
                    }
                    else
                    {
                        // ReCaptcha defaults to english.
                        localizedHtml = html;
                    }
                }
                catch (Exception)
                {

                    throw;
                }
                finally
                {
                    htmlWriter.Dispose();   
                }
                              
                return localizedHtml;
            }
        }
    }
}
